from config.db_connection import DBConnection
import pymysql

class Product:
    """商品信息数据类"""
    
    def __init__(self, product_data=None):
        """初始化商品信息"""
        if product_data:
            self.id = product_data.get('id', 0)
            self.product_name = product_data.get('product_name', '')
            self.price = float(product_data.get('price', 0.0))
            self.sales = product_data.get('sales', 0)
        else:
            self.id = 0
            self.product_name = ''
            self.price = 0.0
            self.sales = 0
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'id': self.id,
            'product_name': self.product_name,
            'price': self.price,
            'sales': self.sales
        }
    
    def __str__(self):
        return f"Product(id={self.id}, name='{self.product_name}', price={self.price})"

class ProductModel:
    """商品数据模型"""
    
    @staticmethod
    def add_product(product_name, price):
        """添加商品"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            # 检查商品名是否已存在
            cursor.execute("SELECT id FROM product WHERE product_name = %s", (product_name,))
            if cursor.fetchone():
                print(f"商品 {product_name} 已存在")
                return False
            
            # 插入新商品
            cursor.execute("""
                INSERT INTO product (product_name, price, sales) 
                VALUES (%s, %s, 0)
            """, (product_name, price))
            
            conn.commit()
            print(f"商品 {product_name} 添加成功")
            return True
            
        except pymysql.Error as e:
            print(f"添加商品失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def get_all_products():
        """获取所有商品信息 - 每次都从数据库重新查询"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            cursor.execute("SELECT id, product_name, price, sales FROM product ORDER BY id")
            products = cursor.fetchall()
            
            product_list = []
            for product in products:
                product_data = {
                    'id': product[0],
                    'product_name': product[1],
                    'price': product[2],
                    'sales': product[3]
                }
                product_list.append(Product(product_data))
            
            return product_list
            
        except pymysql.Error as e:
            print(f"获取商品列表失败: {e}")
            return []
        finally:
            cursor.close()
    
    @staticmethod
    def update_product(product_id, product_name=None, price=None):
        """更新商品信息"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            update_fields = []
            params = []
            
            if product_name is not None:
                update_fields.append("product_name = %s")
                params.append(product_name)
            
            if price is not None:
                update_fields.append("price = %s")
                params.append(price)
            
            if not update_fields:
                return False
            
            params.append(product_id)
            sql = f"UPDATE product SET {', '.join(update_fields)} WHERE id = %s"
            cursor.execute(sql, tuple(params))
            
            conn.commit()
            print(f"商品更新成功")
            return True
            
        except pymysql.Error as e:
            print(f"更新商品失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def delete_product(product_id):
        """删除商品"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            cursor.execute("DELETE FROM product WHERE id = %s", (product_id,))
            
            conn.commit()
            print(f"商品删除成功")
            return True
            
        except pymysql.Error as e:
            print(f"删除商品失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()
    
    @staticmethod
    def increment_sales(product_id):
        """增加商品销量"""
        try:
            conn = DBConnection.get_connection()
            cursor = conn.cursor()
            
            cursor.execute("UPDATE product SET sales = sales + 1 WHERE id = %s", (product_id,))
            
            conn.commit()
            return True
            
        except pymysql.Error as e:
            print(f"更新销量失败: {e}")
            conn.rollback()
            return False
        finally:
            cursor.close()